package com.work.studio.net;

import android.util.Log;

import com.work.studio.BuildConfig;
import com.work.studio.utils.Utils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retrofit终端
 */
public class RetrofitClient {

    private RetrofitClient() {
    }

    public static Retrofit getInstance() {
        return Holder.retrofit;
    }

    private static class Holder {
        static OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new LogInterceptor())
                .addInterceptor(new HttpLoggingInterceptor(new HttpLog()).setLevel(HttpLoggingInterceptor.Level.BODY))
                .connectTimeout(60, TimeUnit.SECONDS)//设置超时时间
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();

        static Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://qy.jinweiyun.cn:9300")
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }


    static class HttpLog implements HttpLoggingInterceptor.Logger {
        @Override
        public void log(String message) {
            logLong(message);
        }
    }

    private static class LogInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            //这个chain里面包含了request和response，所以你要什么都可以从这里拿
            Request request = chain.request();

            Headers headerMap = request.headers();
            Log.e("Head--", headerMap.toString());
//            chain.request().newBuilder().build();
//            printParams(request.body());
            if (BuildConfig.DEBUG) {
                if ("POST".equals(request.method())) {
                    if (request.body() instanceof FormBody) {
                        FormBody body = (FormBody) request.body();
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < body.size(); i++) {
                            sb.append(body.name(i) + "=" + body.value(i) + "&");
                        }
                        Log.e("http--", Utils.createLogString("请求地址====>" + request.url(), "请求参数====>" + sb.toString()));
                    }else {
                        RequestBody body = request.body();
                        body.toString();
                        Log.e("http--", Utils.createLogString("请求地址====>" + request.url(), "请求参数====>" + body.toString()));
                    }
                } else {

//                    request.body();

//                    RequestBody body = request.body();
//                    body.toString();
//                    Log.e("http--", Utils.createLogString("请求地址====>" + request.url(), "请求参数====>" + body.toString()));
                }
            }

            Response response = chain.proceed(request);
            //这里不能直接使用response.body().string()的方式输出日志
            //因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一个新的response给应用层处理
            if (BuildConfig.DEBUG) {
                ResponseBody responseBody = response.peekBody(1024 * 1024);
                String value = responseBody.string();
//                Log.e("http--", Utils.createLogString("返回结果====>" + value));

                logLong("返回结果====>" + value);
            }
            return response;
        }
    }

    private static void logLong(String log) {
        if (log.length() > 4000) {
            for (int i = 0; i < log.length(); i += 4000) {
                if (i + 4000 < log.length())
                    Log.d("http--", log.substring(i, i + 4000));
                else
                    Log.d("http--", log.substring(i, log.length()));
            }
        } else {
            Log.d("http--", log);
        }
    }

}
